/**
 * 兼容H5和小程序的图片转base64方法
 * @param {string} filePath - 图片路径（本地路径、临时路径、网络路径）
 * @param {Object} options - 配置选项
 * @param {string} options.mimeType - 指定MIME类型，默认自动检测
 * @param {number} options.quality - 压缩质量（0-1），默认0.8
 * @param {number} options.maxWidth - 最大宽度，默认不限制
 * @param {number} options.maxHeight - 最大高度，默认不限制
 * @returns {Promise<string>} base64字符串
 */
const imageToBase64 = (filePath, options = {}) => {
    return new Promise((resolve, reject) => {
        // 默认配置
        const config = {
            mimeType: 'image/jpeg',
            quality: 0.8,
            maxWidth: 0,
            maxHeight: 0,
            ...options
        };
        
        // 如果是base64格式，直接返回
        if (filePath.startsWith('data:')) {
            resolve(filePath);
            return;
        }
        
        // 判断运行环境
        const isH5 = typeof window !== 'undefined' && window.document;
        const isMP = typeof wx !== 'undefined' || typeof my !== 'undefined' || typeof tt !== 'undefined';
        
        // 自动检测图片类型
        if (!config.mimeType) {
            config.mimeType = detectImageType(filePath);
        }
        console.log(isH5,isMP);
        if (isMP) {
            // 小程序环境
            handleMiniProgram(filePath, config, resolve, reject);
            // handleH5(filePath, config, resolve, reject);
        } else if (isH5) {
            // H5环境
            handleH5(filePath, config, resolve, reject);
        } else {
            // 其他环境（如App）
            handleApp(filePath, config, resolve, reject);
        }
    });
};

/**
 * 检测图片类型
 */
const detectImageType = (filePath) => {
    if (filePath.includes('.png')) return 'image/png';
    if (filePath.includes('.gif')) return 'image/gif';
    if (filePath.includes('.webp')) return 'image/webp';
    if (filePath.includes('.bmp')) return 'image/bmp';
    return 'image/jpeg';
};

/**
 * 处理小程序环境
 */
const handleMiniProgram = (filePath, config, resolve, reject) => {
    // 先压缩图片（如果需要）
    if (config.maxWidth > 0 || config.maxHeight > 0) {
        uni.compressImage({
            src: filePath,
            quality: Math.floor(config.quality * 100),
            success: (compressRes) => {
                readFileAsBase64(compressRes.tempFilePath, config, resolve, reject);
            },
            fail: (err) => {
                console.warn('图片压缩失败，使用原图:', err);
                readFileAsBase64(filePath, config, resolve, reject);
            }
        });
    } else {
        readFileAsBase64(filePath, config, resolve, reject);
    }
};

/**
 * 读取文件为base64（小程序通用方法）
 */
const readFileAsBase64 = (filePath, config, resolve, reject) => {
    uni.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => {
            const base64Data = `data:${config.mimeType};base64,${res.data}`;
            resolve(base64Data);
        },
        fail: (err) => {
            console.error('小程序读取文件失败:', err);
            reject(new Error(`读取文件失败: ${err.errMsg || '未知错误'}`));
        }
    });
};

/**
 * 处理H5环境
 */
const handleH5 = (filePath, config, resolve, reject) => {
    // 如果是网络图片，先下载
    if (filePath.startsWith('http') || filePath.startsWith('//')) {
        downloadImageForH5(filePath, config, resolve, reject);
    } else {
        // 本地文件（可能是input file选择的文件）
        processLocalImageForH5(filePath, config, resolve, reject);
    }
};

/**
 * H5环境下载网络图片
 */
const downloadImageForH5 = (filePath, config, resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    
    img.onload = function() {
        processImageWithCanvas(img, config, resolve, reject);
    };
    
    img.onerror = function(err) {
        reject(new Error(`图片加载失败: ${err}`));
    };
    
    img.src = filePath;
};

/**
 * H5环境处理本地图片
 */
const processLocalImageForH5 = (filePath, config, resolve, reject) => {
    // 如果是File对象
    if (filePath instanceof File) {
        const reader = new FileReader();
        reader.onload = function(e) {
            resolve(e.target.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(filePath);
        return;
    }
    
    // 如果是blob URL
    if (filePath.startsWith('blob:')) {
        fetch(filePath)
            .then(response => response.blob())
            .then(blob => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    resolve(e.target.result);
                };
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            })
            .catch(reject);
        return;
    }
    
    // 其他情况，当作普通图片处理
    const img = new Image();
    img.onload = function() {
        processImageWithCanvas(img, config, resolve, reject);
    };
    img.onerror = reject;
    img.src = filePath;
};

/**
 * 使用Canvas处理图片（H5环境）
 */
const processImageWithCanvas = (img, config, resolve, reject) => {
    try {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        let { width, height } = calculateSize(img, config);
        
        canvas.width = width;
        canvas.height = height;
        
        // 绘制图片
        ctx.drawImage(img, 0, 0, width, height);
        
        // 获取base64
        const dataURL = canvas.toDataURL(config.mimeType, config.quality);
        resolve(dataURL);
    } catch (error) {
        reject(new Error(`Canvas处理失败: ${error.message}`));
    }
};

/**
 * 计算图片尺寸
 */
const calculateSize = (img, config) => {
    let width = img.width;
    let height = img.height;
    
    if (config.maxWidth > 0 && width > config.maxWidth) {
        const ratio = config.maxWidth / width;
        width = config.maxWidth;
        height = height * ratio;
    }
    
    if (config.maxHeight > 0 && height > config.maxHeight) {
        const ratio = config.maxHeight / height;
        height = config.maxHeight;
        width = width * ratio;
    }
    
    return { width: Math.round(width), height: Math.round(height) };
};

/**
 * 处理App环境（使用5+ API）
 */
const handleApp = (filePath, config, resolve, reject) => {
    if (typeof plus !== 'undefined') {
        plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
            entry.file((file) => {
                const reader = new plus.io.FileReader();
                reader.onloadend = (e) => {
                    resolve(e.target.result);
                };
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        }, reject);
    } else {
        reject(new Error('不支持的运行环境'));
    }
};

// 导出方法
export default imageToBase64;